package com.yjf.ljr.activity;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;

public class WvWithdrawActivity extends IjActivity{

	@ID("wvUniversity_schoollife")
	private WebView mWvContent;
	@ID("llError_webview")
	private LinearLayout mLlError;
	
	private String url;
	private String title;
	private boolean mIsLoad = true;
	private String appCacheDir;
	
	private String okReturnStr;
	
	private String returnStr; 
	
	private final String RESULT_URL = "userManage/topUp/resultForApp";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_pwd_webview);
		initContent();
	}
	
	@SuppressLint("SetJavaScriptEnabled") 
	private void initContent() {
		url = getIntent().getStringExtra("url");
		title = getIntent().getStringExtra("title");
		okReturnStr = CommonData.LOGIN_GOTO_URL+RESULT_URL;
		returnStr = getIntent().getStringExtra("returnStr");
		if(!TextUtils.isEmpty(returnStr)) {
			returnStr = CommonData.LOGIN_GOTO_URL+returnStr;
		}
		((TextView) findViewById(R.id.tv_title)).setText(title);
		setLeftBtnClick();
		
		WebSettings settings = mWvContent.getSettings();
		mWvContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		settings.setSupportZoom(false);
		settings.setBuiltInZoomControls(false);
		settings.setDomStorageEnabled(true);
		settings.setAppCacheMaxSize(1024 * 1024 * 9);// 设置缓冲大小
		appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
		settings.setAppCachePath(appCacheDir);
		settings.setAllowFileAccess(true);
		settings.setAppCacheEnabled(true);
		settings.setJavaScriptEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//		mWvContent.addJavascriptInterface(new JavaScriptInterface(), "bornClient");
		mWvContent.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				if(!TextUtils.isEmpty(returnStr) && !TextUtils.isEmpty(url) && url.startsWith(returnStr)) {
					mWvContent.setVisibility(View.GONE);
				}				
				if (!TextUtils.isEmpty(url) && url.startsWith(okReturnStr) && url.contains("code")) {
					String code = "";
					try{
						code = Uri.parse(url).getQueryParameter("code");
					} catch (Exception e) {
						e.printStackTrace();
					}			
					if("BIZ_PROCESSING".equalsIgnoreCase(code)) {
						if(!TextUtils.isEmpty(title) && title.contains("提现")) {
							showToast("提现成功！");
						} else {
							showToast("充值成功！");
						}
						setResult(RESULT_OK);
					} else {
						String content = Uri.parse(url).getQueryParameter("message");
						if(!TextUtils.isEmpty(title) && title.contains("提现")) {														
							if(!TextUtils.isEmpty(content)) {
								showToast(content);
							} else {
								showToast("提现失败！");
							}
						} else {
							if(!TextUtils.isEmpty(content)) {
								showToast(content);
							} else {
								showToast("充值失败！");
							}
						}
						setResult(RESULT_CANCELED);
					}					
					WvWithdrawActivity.this.finish();
					return;
				}
				showProgressDialog();
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				dismissProgressDialog();
				mLlError.setVisibility(View.VISIBLE);
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed();
			}

			@Override
			public void onPageFinished(WebView view, String url) {				
				super.onPageFinished(view, url);
				dismissProgressDialog();
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if(url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(intent);
					return true;
				} else {
					return false;
				}
			}		
		});
		mWvContent.setWebChromeClient(new WebChromeClient());

		mLlError.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mWvContent.reload();
			}
		});
		mLlError.setVisibility(View.GONE);
		synCookies(this,CommonData.LOGIN_GOTO_URL,url);
		mWvContent.loadUrl(url);
		
	}

	@Override
	protected void onDestroy() {
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		super.onDestroy();
	}

	
	public static void synCookies(Context context, String url, String anotherUrl) {
		String myCookies = "";
		if (!TextUtils.isEmpty(CommonData.SESSIONID) && CommonData.SESSIONID.startsWith("[")
				&& CommonData.SESSIONID.endsWith("]")) {
			myCookies = CommonData.SESSIONID.substring(1, CommonData.SESSIONID.length() - 1);
		}
		CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
		cookieSyncManager.sync();
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		if (!TextUtils.isEmpty(myCookies)) {
			String[] datas = myCookies.split(",");
			for (String data : datas) {
				cookieManager.setCookie(url, data);
				cookieManager.setCookie(anotherUrl, data);
			}
		}
		CookieSyncManager.getInstance().sync();
	}
	
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	 	return false;
	}
	
}
